/*******************************************************************************
 * Copyright (c) 2011 Erik Byström.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package se.slackers.automatunes.ui;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

/**
 * @author Erik Byström
 * 
 */
public class IntParameter extends BaseParameter<Integer, JTextField> {
	private Integer value;
	private final int min;
	private final int max;

	private final List<JTextField> fields = new LinkedList<JTextField>();
	private boolean enable = true;

	private final DocumentListener listener = new DocumentListener() {
		@Override
		public void removeUpdate(final DocumentEvent e) {
			updated(e);
		}

		@Override
		public void insertUpdate(final DocumentEvent e) {
			updated(e);
		}

		@Override
		public void changedUpdate(final DocumentEvent e) {
			updated(e);
		}
	};

	public IntParameter(final String name, final int value, final int min, final int max) {
		super(name);
		this.value = value;
		this.min = min;
		this.max = max;
	}

	@Override
	public Integer value() {
		return value;
	}

	@Override
	public void value(final Integer value) {
		this.value = value;
		for (final JTextField field : fields) {
			field.setText(String.valueOf(value));
		}
	}

	@Override
	public void disconnect() {
		if (fields.isEmpty()) {
			return;
		}

		for (final JTextField field : fields) {
			field.getDocument().removeDocumentListener(listener);
		}

		fields.clear();
	}

	@Override
	public Parameter<Integer, JTextField> connect(final JTextField field) {
		fields.add(field);
		field.setText(String.valueOf(value));

		field.getDocument().addDocumentListener(listener);
		field.addFocusListener(new FocusListener() {
			@Override
			public void focusLost(final FocusEvent arg0) {
				new SwingWorker<String, Object>() {
					@Override
					protected String doInBackground() throws Exception {
						try {
							enable = false;
							value(value);
						} finally {
							enable = true;
						}
						return null;
					}
				}.execute();
			}

			@Override
			public void focusGained(final FocusEvent arg0) {
			}
		});

		field.addHierarchyListener(new HierarchyListener() {
			@Override
			public void hierarchyChanged(final HierarchyEvent event) {
				if ((event.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
					if (!event.getChanged().isDisplayable()) {
						field.removeHierarchyListener(this);
						field.getDocument().removeDocumentListener(listener);
						fields.remove(field);
					}
				}
			}
		});

		return this;
	}

	protected void updated(final DocumentEvent e) {
		if (!enable) {
			return;
		}
		try {
			final Document doc = e.getDocument();
			final String text = doc.getText(0, doc.getLength());
			value = Math.max(min, Math.min(max, Integer.parseInt(text)));
		} catch (final Exception ex) {
			System.err.println(ex.getMessage());
		}
	}

	@Override
	public String toString() {
		return name + "=" + String.valueOf(value);
	}

	@Override
	public JComponent create() {
		final JTextField field = new JTextField(5);

		if (tooltip != null) {
			field.setToolTipText(tooltip);
		}

		connect(field);
		return field;
	}
}
